package com.qdsg.ysg.doctor.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseLoginActivity;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.ui.activity.mine.ForgetActivity;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.dialog.RulesDialogFragment;
import com.qdsg.ysg.doctor.util.AES128;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.response.LoginResponse;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.PreferencesHelper;

/**
 * @author Administrator
 * @date 2018/5/25
 */

public class LoginActivity extends BaseLoginActivity {
    @BindView(R.id.edt_user_name)
    EditText edtUserName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.iv_password_hide)
    ImageView ivPasswordHide;
    @BindView(R.id.ll_password)
    LinearLayout llPassword;
    @BindView(R.id.checkbox)
    ImageView checkbox;
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;

    private boolean isCheckBox, isShowPassword = false;
    private ProgressDialog mDialog;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_login;
    }

    @Override
    protected void initViews() {
        edtUserName.setText(PreferencesHelper.getInstance().getString(this, "username"));
        etPassword.setText(PreferencesHelper.getInstance().getString(this, "password"));
    }

    @Override
    protected void initData() {
        if (PreferencesHelper.getInstance().getBoolean(this, "isCheckBox")) {
            checkbox.setImageResource(R.mipmap.check_focus);
            isCheckBox = true;
            edtUserName.setText(PreferencesHelper.getInstance().getString(this, "username"));
            etPassword.setText(PreferencesHelper.getInstance().getString(this, "password"));
        } else {
            checkbox.setImageResource(R.mipmap.check);
            isCheckBox = false;
        }
        if (PreferencesHelper.getInstance().getBoolean(this, "isAgree")) {
            cbAgree.setChecked(true);
        } else {
            cbAgree.setChecked(false);
        }
    }

    @OnClick({R.id.iv_back, R.id.check_container, R.id.btn_register, R.id.iv_password_hide, R.id.btn_login, R.id.tv_agree, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.check_container:
                if (isCheckBox) {
                    checkbox.setImageResource(R.mipmap.check);
                } else {
                    checkbox.setImageResource(R.mipmap.check_focus);
                }
                isCheckBox = !isCheckBox;
                break;
            case R.id.btn_register:
                ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("2", true);
                applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
                applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

                    @Override
                    public void onConfirm() {
                        startActivity(RegisterActivity.class);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                break;
            case R.id.iv_password_hide:
                if (isShowPassword) {
                    //设置不可见
                    ivPasswordHide.setImageResource(R.mipmap.icon_password_open);
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    //设置可见
                    ivPasswordHide.setImageResource(R.mipmap.icon_password_hide);
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                isShowPassword = !isShowPassword;

                break;
            case R.id.btn_login:
                RestClient.getInstance().clearSession();
                login();
                break;
            case R.id.tv_agree:
                showRulesDialogFragment();
                break;
            case R.id.tv_forget:
                startActivity(new Intent(mContext, ForgetActivity.class));
                break;
            default:
                break;
        }
    }


    private RulesDialogFragment mRulesDialogFragment;

    private void showRulesDialogFragment() {

        mRulesDialogFragment = RulesDialogFragment.newInstance("7");
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }


    private void login() {
        String mPassword = etPassword.getText().toString().trim();
        String mPhone = edtUserName.getText().toString().trim();
        if (UtilString.isEmpty(mPhone)) {
            ToastUtil.showToastCenter(mContext, "请输入院内工号");
            return;
        }

        if (UtilString.isEmpty(mPassword)) {
            ToastUtil.showToastCenter(mContext, "密码不能为空");
            return;
        }
        if (!cbAgree.isChecked()) {
            ToastUtil.showToastCenter(mContext, "请先阅读并同意法律声明及隐私权政策");
            return;
        }

        showLoginDialog(getString(R.string.logining_msg));
        try {
            RestProxy.getInstance().login(AES128.encryptStringAES(mPhone, "7t3e506jaa10xbd4"), AES128.encryptStringAES(mPassword, "7t3e506jaa10xbd4"), "", new Observer<LoginResponse>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(LoginResponse loginResponse) {
                    checkServiceRunning(mContext);
                    SoftKeyboardUtil.hideFraSoftKeyboard(mContext, etPassword);
                    SoftKeyboardUtil.hideFraSoftKeyboard(mContext, edtUserName);
                    BaseApplication.currentUserId = loginResponse.data.userId;
                    BaseApplication.name = loginResponse.data.name;
                    BaseApplication.jobTitle = loginResponse.data.jobTitle;
                    BaseApplication.avatar = loginResponse.data.avatar;
                    BaseApplication.sex = loginResponse.data.sex;
                    BaseApplication.isAudit = loginResponse.data.isAudit;
                    BaseApplication.xyAccount = loginResponse.data.videoAccountDTO.account;
                    BaseApplication.xyPassword = loginResponse.data.videoAccountDTO.password;
                    PreferencesHelper.getInstance().set(mContext, "username", edtUserName.getText().toString());
                    PreferencesHelper.getInstance().set(mContext, "password", etPassword.getText().toString());
                    PreferencesHelper.getInstance().set(mContext, "token", loginResponse.data.token);
                    PreferencesHelper.getInstance().set(mContext, "xyAccount", loginResponse.data.videoAccountDTO.account);
                    PreferencesHelper.getInstance().set(mContext, "xyPassword", loginResponse.data.videoAccountDTO.password);
                    BaseApplication.userType = loginResponse.data.hosType;
                    RestClient.getInstance().token = loginResponse.data.token;
                    PreferencesHelper.getInstance().set(mContext, "isCheckBox", isCheckBox);
                    PreferencesHelper.getInstance().set(mContext, "isAgree", cbAgree.isChecked());
                    dismissLoginDialog();
                    startActivity(MainActivity.class);
                    finish();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    ToastUtil.onError(mContext, e);
                }

                @Override
                public void onComplete() {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showLoginDialog(String msg) {
        if (null == mDialog) {
            mDialog = new ProgressDialog(this);
        }
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setTitle(msg);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.show();
    }

    public void dismissLoginDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        stopService(new Intent(mContext, WebSocketService.class));
    }
}
